package com.xqboss.web.controller.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import com.xqboss.apps.domain.punch.PunchUserSlot;
import com.xqboss.apps.domain.user.UserIdentityRank;
import com.xqboss.apps.domain.user.UserIdentityRankSlot;
import com.xqboss.apps.domain.user.UserRankUpgradeRecord;
import com.xqboss.apps.dto.user.UserIdentitySaveDto;
import com.xqboss.apps.dto.user.UserRankUpgradeRecordDto;
import com.xqboss.apps.service.punch.PunchUserSlotService;
import com.xqboss.apps.service.user.UserIdentityRankService;
import com.xqboss.apps.service.user.UserIdentityRankSlotService;
import com.xqboss.apps.service.user.UserIdentityService;
import com.xqboss.apps.service.user.UserRankUpgradeRecordService;
import com.xqboss.apps.vo.user.UserIdentityDetailVo;
import com.xqboss.apps.vo.user.UserIdentityPreVo;
import com.xqboss.apps.vo.user.UserIdentitySimpleVo;
import com.xqboss.apps.vo.user.UserRankUpgradeRecordVo;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.TreeSelect;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(tags = "用户-身份管理")
@RestController("WebUserIdentityController")
@RequestMapping("/web/user/identity")
public class UserIdentityController {

    @Autowired
    private UserIdentityService userIdentityService;

    @Autowired
    private UserIdentityRankService userIdentityRankService;

    @Autowired
    private UserRankUpgradeRecordService userRankUpgradeRecordService;

    @Autowired
    private UserIdentityRankSlotService userIdentityRankSlotService;
    @Autowired
    private PunchUserSlotService punchUserSlotService;

    /**
     * 身份配置列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:list')")
    @ApiOperation("身份配置列表")
    @GetMapping("/list")
    public R<List<UserIdentitySimpleVo>> list() {
        return R.ok(userIdentityService.simpleList());
    }

    /**
     * 前置身份列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:list')")
    @ApiOperation("前置身份列表")
    @GetMapping("/pre/list")
    public R<List<UserIdentityPreVo>> preIdentityList() {
        List<UserIdentityRank> list = userIdentityRankService.lambdaQuery().eq(UserIdentityRank::getIsHighest, 1).list();
        List<UserIdentityPreVo> voList = new ArrayList<>();
        list.forEach(t -> {
            UserIdentityPreVo vo = new UserIdentityPreVo();
            vo.setIdentityRankId(t.getId());
            vo.setIdentifyName(t.getIdentityName());
            vo.setRankName(t.getName());
            voList.add(vo);
        });
        return R.ok(voList);
    }

    /**
     * 身份配置新增
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:add')")
    @ApiOperation("身份配置新增")
    @RepeatSubmit(interval = 1000, justUrl = true, message = "访问过于频繁，请稍后再试")
    @PostMapping("/add")
    public R add(@Validated @RequestBody UserIdentitySaveDto param) {
        userIdentityService.add(param);
        return R.ok();
    }

    /**
     * 身份配置修改
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:edit')")
    @ApiOperation("身份配置修改")
    @RepeatSubmit(interval = 1000, justUrl = true, message = "访问过于频繁，请稍后再试")
    @PostMapping("/edit")
    public R edit(@Validated @RequestBody UserIdentitySaveDto param) {
        userIdentityService.edit(param);
        return R.ok();
    }

    /**
     * 身份配置详情
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:info')")
    @ApiOperation("身份配置详情")
    @GetMapping("/info")
    public R<UserIdentityDetailVo> add(@RequestParam Long id) {
        return R.ok(userIdentityService.info(id));
    }

    /**
     * 树形结构
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('web:user:identity:list')")
    @ApiOperation("身份段位树形结构")
    @GetMapping("/tree/list")
    public R<List<TreeSelect>> treeList() {
        return R.ok(userIdentityService.treeList());
    }


    @PreAuthorize("@ss.hasPermi('web:user:rankUpgradeRecord:list')")
    @ApiOperation("查询用户升级记录")
    @GetMapping("/list-record")
    public R<List<UserRankUpgradeRecordVo>> rankUpgradeRecord(@Validated UserRankUpgradeRecordDto dto){
        dto.startPageAndOrder();
        List<UserRankUpgradeRecord> userRankUpgradeRecords = userRankUpgradeRecordService.rankUpgradeRecord(dto);
        List<UserRankUpgradeRecordVo> userRankUpgradeRecordVos = userRankUpgradeRecordService.rankUpgradeRecordVo(userRankUpgradeRecords);
        return R.ok(userRankUpgradeRecordVos,userRankUpgradeRecords);
    }

    @PreAuthorize("@ss.hasPermi('web:user:lot:list')")
    @ApiOperation("多卡槽配置列表")
    @GetMapping("/lot-list")
    public R<List<UserIdentityRankSlot>> lotList(){
        List<UserIdentityRankSlot> list = userIdentityRankSlotService.list();
        if (CollUtil.isNotEmpty(list)) {
            List<UserIdentityRank> list1 = this.userIdentityRankService.lambdaQuery()
                    .select(UserIdentityRank::getId, UserIdentityRank::getIdentityName,UserIdentityRank::getName).list();
            if (CollUtil.isNotEmpty(list1)) {
                Map<Long, UserIdentityRank> collect = list1.stream().collect(Collectors.toMap(UserIdentityRank::getId, Function.identity()));
                list.forEach(l->l.setIdentityRankName(collect.get(l.getIdentityRankId()).getIdentityName() + collect.get(l.getIdentityRankId()).getName()));
            }
        }
        return R.ok(list);
    }

    @PreAuthorize("@ss.hasPermi('web:user:lot:info')")
    @ApiOperation("多卡槽配置信息")
    @GetMapping("/lot-info/{id}")
    public R<UserIdentityRankSlot> lotInfo(@PathVariable String id){
        UserIdentityRankSlot byId = userIdentityRankSlotService.getById(id);
        Assert.notNull(byId,()->new ServiceException("未查询到配置信息~"));
        if (byId.getIdentityRankId()!=null) {
            UserIdentityRank byId1 = this.userIdentityRankService.getById(byId.getIdentityRankId());
            if (ObjUtil.isNotEmpty(byId1)) {
                Long count = this.userIdentityRankService.lambdaQuery().eq(UserIdentityRank::getIdentityId, byId1.getIdentityId()).count();
                byId.setIdentityId(count>1?byId1.getIdentityId():null);
            }
        }
        return R.ok(byId);
    }

    @PreAuthorize("@ss.hasPermi('web:user:lot:addOrEdit')")
    @Log(title = "多卡槽更新", businessType = BusinessType.INSERT_OR_UPDATE)
    @ApiOperation("多卡槽新增/编辑（携带id）")
    @PostMapping("/lot-addOrEdit")
    public R<String> addOrEdit(@RequestBody @Validated UserIdentityRankSlot slot){
        Assert.isTrue(userIdentityRankSlotService.saveOrUpdate(slot),()->new ServiceException(String.format("%s失败",slot.getId()==null?"新增":"编辑")));
        return R.ok_msg(String.format("%s成功",slot.getId()==null?"新增":"编辑"));
    }

    @PreAuthorize("@ss.hasPermi('web:user:lot:del')")
    @Log(title = "多卡槽删除", businessType = BusinessType.DELETE)
    @ApiOperation("多卡槽删除")
    @GetMapping("/lot-del")
    public R<String> del(@RequestParam Long id) {
        Assert.isTrue(userIdentityRankSlotService.removeById(id), () -> new ServiceException("删除失败"));
        // 删除用户现有的卡槽
        boolean remove = punchUserSlotService.lambdaUpdate().eq(PunchUserSlot::getSlotId, id).remove();
        if (!remove) {
            throw new ServiceException("删除用户卡槽失败");
        }
        return R.ok_msg("删除成功");
    }

}
